package com.study.common.util;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 *  http请求工具类，需要配置 RestTemplate 才能使用
 *  @author: Lizq
 *  @Date: 2019/12/5 10:19
 */
@Component
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @description post调用
     * @author hw
     * @date 2020/10/9 19:39:13
     * @param url:
     * @param params:
     * @return java.lang.String
     */
    public String postForObject(String url, Map<String, Object> params) {
        try {
            //设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(params, httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
            HttpStatus statusCode = responseEntity.getStatusCode();
            if(statusCode.equals(HttpStatus.OK)) {
                return responseEntity.getBody();
            } else {
                logger.error("**********接口请求失败，url = " + url + ", 参数：" + JSON.toJSONString(params) + "返回码：" + statusCode.value());
                return null;
            }
        } catch (Exception e) {
            logger.error("**********请求接口出错：url = " + url + "， 参数：" + JSON.toJSONString(params), e);
            throw e;
        }
    }


    /***
     * @description get调用
     * @author hw
     * @date 2020/10/9 19:39:50
     * @param url:
     * @param params:
     * @return java.lang.String
     */
    public String getForObject(String url, Map<String,Object> params) {
        url = doUrl(url, params);
        try {
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            HttpStatus statusCode = responseEntity.getStatusCode();
            if(statusCode.equals(HttpStatus.OK)) {
                return responseEntity.getBody();
            } else {
                logger.error("-----------接口请求失败，url = " + url + ", 参数：" + params + "返回码：" + statusCode.value());
                return null;
            }
        } catch (Exception e) {
            logger.error("------------请求接口出错：url = " + url + "， 参数：" + params, e);
            throw e;
        }
    }

    /***
     * @description 拼接url
     * @author hw
     * @date 2020/10/9 19:40:00
     * @param url:
     * @param params:
     * @return java.lang.String
     */
    private static String doUrl(String url, Map<String,Object> params) {
        //判断params是否为空
        if (params == null || params.isEmpty()) {
        } else {
            //不为空进行url拼接
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                stringBuilder.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
            stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
            url = url + stringBuilder.toString();
        }
        return url;
    }

    public static void main(String[] args) {
        String url = "http://10.56.0.165:30005/verification-be/sdLogin/loginByEncryption?encryption=22880cd7e72adcbdbabb591c2c6850b8&id=84906566782c48219s5s5e8d030f58e9";
        HttpResponse response = cn.hutool.http.HttpUtil.createGet(url).execute();
        List<String> cookies = response.headerList("Set-Cookie");
        String cookie = "";
        for(String e : cookies){
            cookie = cookie.concat(e).concat(";");
        }
        System.out.println(cookie);
    }
}
